import * as vscode from 'vscode';
import { ChatProvider } from './chatProvider';
import { CodebaseAnalyzer } from './codebaseAnalyzer';
import { CompletionProvider } from './completionProvider';
import { DeepseekAPI } from './deepseekAPI';
import { CodeAssistant } from './codeAssistant';
import { SnippetGenerator } from './snippetGenerator';
import { SUPPORTED_LANGUAGES, isSupportedLanguage } from './languageSupport';
import { LanguageFeatureProvider } from './languageFeatures';
import { ToolsViewProvider } from './views/toolsView';
import { ChatViewProvider } from './views/chatViewProvider';
import { ChatHistoryManager } from './chatHistory';

export function activate(context: vscode.ExtensionContext) {
    // 获取 API Key
    const apiKey = vscode.workspace.getConfiguration('deepseek').get('apiKey');
    
    // 初始化 DeepseekAPI 和 ChatHistoryManager
    const deepseekAPI = new DeepseekAPI();
    const historyManager = new ChatHistoryManager(context);
    const chatProvider = new ChatProvider(context, deepseekAPI, historyManager);
    const codebaseAnalyzer = new CodebaseAnalyzer(deepseekAPI);
    const codeAssistant = new CodeAssistant(deepseekAPI);
    const snippetGenerator = new SnippetGenerator(deepseekAPI);

    const languageFeatures = new LanguageFeatureProvider(deepseekAPI);

    // 注册诊断集合
    const diagnosticCollection = vscode.languages.createDiagnosticCollection('deepseek');
    context.subscriptions.push(diagnosticCollection);

    // 监听文档变化
    let diagnosticTimer: NodeJS.Timeout;
    const updateDiagnostics = async (document: vscode.TextDocument) => {
        if (!document || !isSupportedLanguage(document.languageId)) return;

        clearTimeout(diagnosticTimer);
        diagnosticTimer = setTimeout(async () => {
            const diagnostics = await languageFeatures.provideDiagnostics(document);
            diagnosticCollection.set(document.uri, diagnostics);
        }, 1000);
    };

    // 注册代码操作提供程序
    const codeActionProvider = vscode.languages.registerCodeActionsProvider(
        SUPPORTED_LANGUAGES.map(lang => ({ scheme: 'file', language: lang.id })),
        {
            provideCodeActions: (document, range, context) => 
                languageFeatures.provideCodeActions(document, range, context)
        },
        {
            providedCodeActionKinds: [vscode.CodeActionKind.QuickFix]
        }
    );

    // 注册代码镜头提供程序
    const codeLensProvider = vscode.languages.registerCodeLensProvider(
        SUPPORTED_LANGUAGES.map(lang => ({ scheme: 'file', language: lang.id })),
        {
            provideCodeLenses: (document) => 
                languageFeatures.provideCodeLenses(document)
        }
    );

    // 注册命令
    let startChat = vscode.commands.registerCommand('deepseek.startChat', () => {
        chatProvider.show();
    });

    let analyzeCode = vscode.commands.registerCommand('deepseek.analyzeCode', async () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            const text = editor.document.getText();
            await codebaseAnalyzer.analyze(text);
        }
    });

    let suggestChanges = vscode.commands.registerCommand('deepseek.suggestChanges', async () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            const text = editor.document.getText();
            const suggestions = await codebaseAnalyzer.suggestChanges(text);
            // 显示建议并等待确认
            const result = await vscode.window.showInformationMessage(
                'Apply suggested changes?',
                'Yes',
                'No'
            );
            if (result === 'Yes') {
                // 应用更改
                await codebaseAnalyzer.applyChanges(editor, suggestions);
            }
        }
    });

    // 注册代码补全提供程序
    const completionProvider = vscode.languages.registerCompletionItemProvider(
        ['javascript', 'typescript', 'python', 'java'], // 支持的语言
        {
            provideCompletionItems: (document, position, token, context) => {
                return codeAssistant.provideCompletions(document, position, context);
            }
        },
        '.', // 触发字符
        ' ' // 空格也触发补全
    );

    // 注册代码重构命令
    const suggestRefactorings = vscode.commands.registerCommand(
        'deepseek.suggestRefactorings',
        async () => {
            const editor = vscode.window.activeTextEditor;
            if (editor) {
                const refactorings = await codeAssistant.provideRefactorings(editor.document);
                
                // 显示重构建议
                for (const refactoring of refactorings) {
                    const result = await vscode.window.showInformationMessage(
                        `${refactoring.title}\n${refactoring.description}`,
                        '应用更改',
                        '取消'
                    );
                    
                    if (result === '应用更改') {
                        await codeAssistant.applyRefactoring(refactoring);
                    }
                }
            }
        }
    );

    // 注册代码片段生成命令
    const generateSnippet = vscode.commands.registerCommand(
        'deepseek.generateSnippet',
        async () => {
            // 选择语言
            const language = await vscode.window.showQuickPick(
                SUPPORTED_LANGUAGES.map(lang => ({
                    label: lang.aliases[0],
                    description: `${lang.extensions.join(', ')}`,
                    languageId: lang.id
                })),
                {
                    placeHolder: '选择编程语言'
                }
            );

            if (!language) return;

            // 输入描述
            const description = await vscode.window.showInputBox({
                prompt: '请描述你想要生成的代码片段',
                placeHolder: '例如：创建一个带有错误处理的异步函数'
            });

            if (!description) return;

            // 获取当前选中的代码作为上下文
            let context = '';
            const editor = vscode.window.activeTextEditor;
            if (editor?.selection && !editor.selection.isEmpty) {
                context = editor.document.getText(editor.selection);
            }

            try {
                vscode.window.showInformationMessage('正在生成代码片段...');
                
                const snippet = await snippetGenerator.generateSnippet(
                    description,
                    language.languageId,
                    context
                );

                // 预览并保存
                const preview = await vscode.window.showTextDocument(
                    await vscode.workspace.openTextDocument({
                        content: snippet.body.join('\n'),
                        language: language.languageId
                    })
                );

                const save = await vscode.window.showInformationMessage(
                    '是否保存为代码片段？',
                    '保存',
                    '取消'
                );

                if (save === '保存') {
                    await snippetGenerator.saveSnippet(snippet);
                    vscode.window.showInformationMessage(
                        `代码片段已保存！使用 "${snippet.prefix}" 触发。`
                    );
                }
            } catch (error: unknown) {
                if (error instanceof Error) {
                    vscode.window.showErrorMessage('生成代码片段失败：' + error.message);
                } else {
                    vscode.window.showErrorMessage('生成代码片段失败');
                }
            }
        }
    );

    // 注册命令
    const applyRefactoring = vscode.commands.registerCommand(
        'deepseek.applyRefactoring',
        async (document: vscode.TextDocument, refactoring: any) => {
            const edit = new vscode.WorkspaceEdit();
            for (const change of refactoring.changes) {
                for (const textEdit of change.edits) {
                    edit.replace(
                        document.uri,
                        new vscode.Range(
                            document.positionAt(textEdit.start),
                            document.positionAt(textEdit.end)
                        ),
                        textEdit.newText
                    );
                }
            }
            await vscode.workspace.applyEdit(edit);
        }
    );

    // 注册代码库分析命令
    const analyzeCodebase = vscode.commands.registerCommand(
        'deepseek.analyzeCodebase',
        async () => {
            try {
                vscode.window.showInformationMessage('正在分析代码库...');
                
                const analysis = await codebaseAnalyzer.analyzeCodebase({
                    maxFiles: 50,
                    excludePatterns: [
                        'node_modules',
                        'dist',
                        '.git',
                        '*.map',
                        '*.min.*'
                    ]
                });

                // 创建分析结果预览
                const document = await vscode.workspace.openTextDocument({
                    content: JSON.stringify(analysis, null, 2),
                    language: 'json'
                });
                await vscode.window.showTextDocument(document);
            } catch (error: unknown) {
                if (error instanceof Error) {
                    vscode.window.showErrorMessage('代码库分析失败：' + error.message);
                } else {
                    vscode.window.showErrorMessage('代码库分析失败');
                }
            }
        }
    );

    // 注册视图
    const toolsProvider = new ToolsViewProvider();
    vscode.window.registerTreeDataProvider('deepseekTools', toolsProvider);

    // 注册 webview 视图
    const chatViewProvider = new ChatViewProvider(context, deepseekAPI);
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('deepseekChat', chatViewProvider)
    );

    // 监听事件
    context.subscriptions.push(
        vscode.workspace.onDidChangeTextDocument(e => updateDiagnostics(e.document)),
        vscode.workspace.onDidOpenTextDocument(updateDiagnostics),
        codeActionProvider,
        codeLensProvider,
        applyRefactoring,
        analyzeCodebase
    );

    // 初始化当前打开的文档
    if (vscode.window.activeTextEditor) {
        updateDiagnostics(vscode.window.activeTextEditor.document);
    }
}

export function deactivate() {} 